package com.fvision.camera;

import android.app.Application;
import android.content.Intent;
import android.os.Build;
import android.os.Environment;

import com.fvision.camera.service.ForegroundService;
import com.huiying.cameramjpeg.UvcCamera;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.lang.reflect.Field;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created by mayn on 2017/12/20.
 */

public class App extends Application{
    private static App _instance;
    private static final String ROOT_PATH= Environment.getExternalStorageDirectory()+"/uvccameramjpeg/";
    public static final String LOG_PATH=ROOT_PATH+"LOG/";
    /**
     * 测试版本有独立的升级通道，用于内部测试
     */
    public static final boolean isTestVersion = false;
    //public static String current_cutvideo=null;

    @Override
    public void onCreate() {
        UvcCamera.getInstance().SetUploadAdasDataStatus(true) ;
        super.onCreate();
        _instance = this;
        Intent intent = new Intent(getApplicationContext(), ForegroundService.class);
        if (Build.VERSION.SDK_INT >= 26) {
            startForegroundService(intent);
        } else {
            startService(intent);
        }
        createDir();
        recordMessage();
    }

    public static App getInstance() {
        return _instance;
    }

    private void createDir(){
        String ROOT_PATH= Environment.getExternalStorageDirectory()+"/uvccameramjpeg/";
        //String APP_ROOT_PATH = getExternalFilesDir();
        String JPG_PATH=ROOT_PATH+"JPEG/";

        File jpeg=new File(JPG_PATH);
        if(!jpeg.exists()){
            jpeg.mkdirs();
        }

        File log=new File(LOG_PATH);
        if(!log.exists()){
            log.mkdirs();
        }
    }

    private void recordMessage() {
        // TODO Auto-generated method stub
        Thread.setDefaultUncaughtExceptionHandler(
                new Thread.UncaughtExceptionHandler() {

                    @Override
                    public void uncaughtException(Thread thread, Throwable ex) {
//                        MobclickAgent.reportError(sInstance, ex);
                        StringWriter out = new StringWriter();
                        File root = new File(LOG_PATH);
                        if (!root.exists()) {
                            root.mkdirs();
                        }
                        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");
                        String filename = "error" + format.format(new Date(System.currentTimeMillis())) + ".txt";
                        File file = new File(LOG_PATH, filename);
                        PrintWriter err;
                        try {
                            FileOutputStream fos = new FileOutputStream(file);
                            err = new PrintWriter(out);
                            Field[] declaredFields = Build.class
                                    .getDeclaredFields();
                            String devicesMessage = "";
                            for (Field field : declaredFields) {
                                try {
                                    devicesMessage = field.getName() + ":"
                                            + field.get(null);
                                    out.append(devicesMessage + "\n");
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            }
                            ex.printStackTrace(err);
                            fos.write(out.toString().getBytes());
                            fos.close();
                            err.close();
                            out.close();
                        }
                        // TODO Auto-generated method stub
                        // 保存异常到文件中
                        catch (IllegalArgumentException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        } catch (FileNotFoundException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        } catch (IOException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                        // 增强用户体验
//						Intent intent = getPackageManager()
//								.getLaunchIntentForPackage(getPackageName());
//						startActivity(intent);// 复活
                        // android.os.Process.killProcess(Process.myPid());// 自杀
                        android.os.Process.killProcess(android.os.Process.myPid());
                        System.exit(0);
                        try {
                            throw (ex);
                        } catch (Throwable e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                        // 未捕获的异常处理
                        //System.out.println("程序挂了吧。。。" + ex);
                    }
                });
    }
}
